#include "comm.hpp"

int main()
{
    umask(0);
    //创建管道文件
    int n = mkfifo(FIFO_NAME, 0666);
    if(n < 0){
        std::cerr << "mkfifo error" << std::endl;
        return 1;
    }
    std::cout << "fifo create success" << std::endl;

    //打开管道文件
    int fd = open(FIFO_NAME, O_RDONLY);
    if(fd < 0){
        std::cerr << "open error" << std::endl;
        return 2;
    }
    std::cout << "fifo open success, waiting for client to input" << std::endl;

    //读取管道文件
    char buffer[1024];
    while(true){
        int num = read(fd, buffer, sizeof(buffer) - 1);
        if(num > 0){
            buffer[num] = 0;
            std::cout << "client say: " << buffer << std::endl;
        }
        else if(num == 0){
            std::cout << "client close" << std::endl;
            break;
        }
        else{
            std::cerr << "read error" << std::endl;
            break;
        }
    }

    //关闭管道文件
    close(fd);
	std::cout << "close success" << std::endl;

	//删除管道文件
	n = unlink(FIFO_NAME);
	if(n < 0){
		std::cerr<<"unlink error"<<std::endl;
	}
	else{
		std::cout<<"unlink success"<<std::endl;
	}
	

    return 0;
}